package com.ruoyi.WELD.service.impl;
import com.google.common.collect.Lists;
import com.ruoyi.WELD.domain.Weld;
import com.ruoyi.WELD.mapper.DataRBMapper;
import com.ruoyi.WELD.mapper.WeldMapper;
import com.ruoyi.WELD.service.IWeldService;
import com.ruoyi.common.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.validation.Validator;
import java.lang.reflect.Field;
import java.util.*;

@Service
public class WeldServiceImpl implements IWeldService {
    private static final Logger log = LoggerFactory.getLogger(WeldServiceImpl.class);

    @Autowired
    private WeldMapper weldMapper;

    @Autowired
    private DataRBMapper dataRBMapper;

    @Autowired
    private IWeldService iWeldService;


    @Autowired
    protected Validator validator;

    @Override
    public List<Weld> selectWeldList(Weld weld) {
        return weldMapper.selectWeldList(weld);
    }

    @Override
    public Weld selectWeldById(Long id) {
        return weldMapper.selectWeldById(id);
    }

    @Override
    public int insertWeld(Weld weld) {
        return weldMapper.insertWeld(weld);
    }

    @Override
    public int updateWeld(Weld Weld) {
        return weldMapper.updateWeld(Weld);
    }

    @Override
    public int deleteWeldById(Long id) {
        return weldMapper.deleteWeldById(id);
    }

    @Override
    public int deleteWeldByIds(Long[] ids) {
        List<Weld> list = weldMapper.selectWeldByIds(ids);
        for (Weld weld:list){
           dataRBMapper.insertDataRB(weld);
        }
        return weldMapper.deleteWeldByIds(ids);
    }

    @Override
    public List<Weld> selectWeldByIds(Long[] ids) {
        return weldMapper.selectWeldByIds(ids);
    }

    @Override
    public int ClearWeld() {return weldMapper.ClearWeld();}

    @Override
    public String importWeld(List<Weld> weldList, Boolean isUpdateSupport) {
        if (weldList.isEmpty() || weldList == null) {
            throw new ServiceException("导入数据不能为空！");
        }
        weldList.forEach(this::stripSlash);
        Map<String, Weld> weldMap = new HashMap<>();
        for (Weld weld : weldList) {
            weldMap.put(canonKey(weld), weld);
        }
        int successUpdate = 0;
        int successAdd = 0;
        List<Weld> wList = new ArrayList<>();
        List<Weld> list = weldMapper.selectWeldList(new Weld());
        try {
            for (Weld weld : weldMap.values()) {
                boolean isUpdate = true;
                if (list.isEmpty() && successAdd==0) {
                    weldMapper.insertWeld(weld);
                    successAdd++;
                } else {
                    String result = canonKey(weld);
                    for (Weld weld1 : list) {
                        String W1 = canonKey(weld1);
                        if (result.equals(W1)) {
                            weld.setId(weld1.getId());
                            weldMapper.updateWeld(weld);
                            successUpdate++;
                            isUpdate = false;
                            break;
                        }
                    }
                    if (isUpdate) {
                        wList.add(weld);
                    }
                }
            }
        } catch (Exception e) {
            return "数据在更新时出现错误";
        }
        if (!wList.isEmpty()) {
            try {
                weldMapper.insertBatch(wList);
                successAdd += wList.size();
            } catch (Exception e) {
//                // ① 控制台看完整堆栈
//                e.printStackTrace();
//                // ② 返回给前端，页面就能弹出
//                return "批量导入失败，原因：" + e.getMessage() + "，详情见后台日志";
                return insertOneByOne(wList);
            }
            return "数据已经全部导入,完成更新共:" + successUpdate + "条。完成新增:" + successAdd + "条 。";
        }
        return "数据全部更新完成,完成更新:"+weldMap.values().size()+"条";
    }
    private String insertOneByOne(List<Weld> weldList) {
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Weld weld : weldList){
            try {
                weldMapper.insertWeld(weld);
                successNum++;
                successMsg.append("<br/>" ).append( successNum).append("、数据Welding ").append(" 导入成功");
            }catch (Exception e){
                failureNum++;
                failureMsg.append("<br/>" ).append(failureNum).append("、数据Welding ").append(" 导入失败");
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "逐条导入共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "逐条导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    private static String canonKey(Weld w) {
        List<String> segments = new ArrayList<>();
        segments.add(val(w.getMaterial1()) + "|" + val(w.getMaterialThickness1()));
        segments.add(val(w.getMaterial2()) + "|" + val(w.getMaterialThickness2()));
        segments.add(val(w.getMaterial3()) + "|" + val(w.getMaterialThickness3()));
        segments.add(val(w.getMaterial4()) + "|" + val(w.getMaterialThickness4()));
        segments.add(val(w.getGumming1()));
        segments.add(val(w.getGumming2()));
        segments.add(val(w.getGumming3()));
        //不参与逆序的段
        List<String> fixSegs = Arrays.asList(val(w.getParametricForm()), val(w.getElectrodeForm()));

        List<String> fwd = new ArrayList<>(segments);
        List<String> rev = new ArrayList<>(segments);
        Collections.reverse(rev);

        List<String> 代表 = fwd;
        if (rev.toString().compareTo(fwd.toString()) < 0) {   // 简单比较，够用
            代表 = rev;
        }
        List<String> all = new ArrayList<>(代表);
        all.addAll(fixSegs);
        return String.join("||", all);
    }
    // 把 null 转成字符串 ""
    private static String val(Object o) {
        return o == null ? "" : o.toString();
    }
    private void stripSlash(Weld weld) {
        Field[] fields = weld.getClass().getDeclaredFields();
        for (Field f : fields) {
            f.setAccessible(true);
            try {
                if (f.getType() == String.class) {
                    String old = (String) f.get(weld);
                    if (old != null) {
                        String cleaned = old.replace("\\", "")
                                .replace("＼", "")
                                .replace("#N/A","");
                        f.set(weld, cleaned);
                    }
                }
            } catch (IllegalAccessException ignored) {
                // 忽略无法访问的字段
            }
        }
    }
}
